package com.silverbox.sweeporder.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestContext
{
    public static HttpServletRequest getRequest()
    {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        return request;
    }

    public static HttpSession getSession()
    {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest().getSession();
        return session;
    }

    public static ServletContext getServletContext()
    {
        ServletContext session = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest().getSession()
                .getServletContext();
        return session;
    }

    public static String getRootPath()
    {
        return getServletContext().getRealPath("/");
    }
    
    /**
	 * 获取请求参数
	 */
	@SuppressWarnings("unchecked")
	public static String requestParams(HttpServletRequest request){
		StringBuffer result = new StringBuffer();
		Map<String, String[]> params = request.getParameterMap();
		if(params!=null&&params.size()>0){
			for (String key : params.keySet()) {
				String[] values = params.get(key);
				for (int i = 0; i < values.length; i++) {
					String value = values[i];
					result.append(key+"="+value+"&");
				}
			} 
			result=result.deleteCharAt(result.length()-1);
		}
		
		return result.toString();
	}
	
	 /**
     * 获取所有request请求参数key-value
     * @param request
     * @return
     */
	 public static Map<String, String> getRequestParams(HttpServletRequest request){
	        
        Map<String, String> params = new HashMap<String, String>();
        if(null != request){
            Set<String> paramsKey = request.getParameterMap().keySet();
            for(String key : paramsKey){
                params.put(key, request.getParameter(key));
            }
        }
        return params;
    }
}